<template>
  <el-dialog v-model="visible" title="分配角色" width="400px" @close="emit('close')">
    <el-form :model="form" label-width="80px">
      <el-form-item label="用户角色">
        <el-checkbox-group v-model="form.FRoleIds">
          <el-checkbox v-for="role in roleOptions" :key="role.FId" :label="role.FId">
            {{ role.FName }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>

    <template #footer>
      <el-button @click="emit('close')">取消</el-button>
      <el-button type="primary" @click="submit">保存</el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { getUserRoles, updateUserRoles } from "@/api/modules/permission";
import { ElMessage } from "element-plus";
import { Permission } from "@/api/interface/permission";

const props = defineProps<{ userId: string }>();
const emit = defineEmits(["close", "refresh"]);

const visible = ref(true);

// 表单数据
const form = reactive<{ FRoleIds: string[] }>({ FRoleIds: [] });
// 角色列表
const roleOptions = ref<Permission.UserRole[]>([]);

onMounted(async () => {
  const roles = await getUserRoles(props.userId);
  roleOptions.value = roles.data;
  form.FRoleIds = roles.data.filter(r => r.FHasRole).map(r => r.FId);
});

const submit = async () => {
  await updateUserRoles({ FUserId: props.userId, FRoleIds: form.FRoleIds });
  ElMessage.success("角色更新成功");
  emit("refresh");
  emit("close");
};
</script>

<style scoped>
.el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}
</style>
